<template>
  <div class="countdown">
    <h2>京西秒杀</h2>
    <div class="countdown-info">
      <span>{{title}}</span>
      点场 倒计时
    </div>
    <div class="countdown-time">
      <span>{{hour}}</span>
      <strong>:</strong>
      <span>{{minute}}</span>
      <strong>:</strong>
      <span>{{sec}}</span>
    </div>
  </div>
</template>

<script>
export default {
  // 定义属性
  props: {
    title: {
      type: String,
      required: true
    },
    // 定义秒杀开始的时间
    start: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      timer: null, // 定时器
      hour: "", // 时
      minute: "", // 分
      sec: "" // 秒
    };
  },
  mounted() {
    this.timer = setInterval(this.compute, 1000)
  },
  beforeDestroy() {
    clearInterval(this.timer)
  },
  methods: {
    leftPad(data) {
      return data > 9 ? data : "0" + data
    },
    compute() {
      // 计算开始时间到现在所剩余的秒数
      let now = parseInt(Date.now() / 1000) // 当前秒杀
      let start = parseInt(new Date(this.start).getTime() / 1000) // 秒杀开始时间的秒数
      let leftTime = start - now // 距离开始时间剩余的秒数
      // 判断时间剩余 归零
      if (leftTime <= 0) {
        this.hour = "00"
        this.minute = "00"
        this.sec = "00"
        clearInterval(this.timer)
      } else {
        // 剩余的小时
        this.hour = this.leftPad(parseInt(leftTime / 3600))
        // 剩余的分钟
        this.minute = this.leftPad(parseInt((leftTime % 3600 ) / 60))
        // 剩余的秒数
        this.sec = this.leftPad((leftTime % 3600) % 60)
      }
    }
  },
};
</script>

<style lang="scss">
  .countdown {
    padding: 35px 0 25px;
    color: #fff;
    text-align: center;
    background: url("https://misc.360buyimg.com/mtd/pc/index_2019/1.0.0/assets/img/613f39ecb60e42dfec798a4ffc0bc012.png") no-repeat;
    background-size: cover;
    h2 {
      margin-bottom: 90px;
      font-size: 32px;
    }
    &-info {
      font-size: 10px;
      span {
        font-size: 18px;
      }
    }
    &-time {
      margin-top: 10px;
      span {
        padding: 5px;
        font-size: 20px;
        background: #000;
      }
      strong {
        margin: 0 5px;
        font-size: 18px;
      }
    }
  }
</style>